package cl.uchile.sketchpad.services;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cl.uchile.sketchpad.persistance.dao.SubjectVersionDao;
import cl.uchile.sketchpad.persistance.dao.UserDAO;
import cl.uchile.sketchpad.persistance.model.SubjectVersion;
import cl.uchile.sketchpad.persistance.model.User;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private SubjectVersionDao subjectVersionDao;

	@Override
	@Transactional(readOnly = true)
	public User findById(Integer id) {
		return this.userDAO.findById(id);
	}

	@Override
	@Transactional(readOnly = true)
	public User findByUsername(String username) {
		return this.userDAO.findByUsername(username);
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<User> getAll() {
		return userDAO.getAll();
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<User> getTVs() {
		return userDAO.getTVs();
	}

	@Override
	@Transactional
	public User getFenUser(String username) {
		return userDAO.getFenUser(username);
	}
	
	@Override
	@Transactional
	public User getGuestUser(String name, String lastName) {
		User user = userDAO.getGuestUser(name, lastName);
		List<SubjectVersion> subjectVersions = user.getSubjectVersions();
		subjectVersions.add(this.subjectVersionDao.findGuestSubject());
		userDAO.persist(user);
		return user;
	}

	@Override
	public void persist(User user) {
		this.userDAO.persist(user);
	}

	@Override
	public User findByMail(String mail) {
		return this.userDAO.findByMail(mail);
	}
	
	@Override
	@Transactional
	public User getUser(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		session.setMaxInactiveInterval(-1);
		if ( session.getAttribute("user") != null )
			return this.findById( ((User)session.getAttribute("user")).getId() );
		else
			return null;
	}
}
